<template>
  <view>
    <!-- 分层购物车 -->
    <block v-if="isNotEmpty">
      <view class="container-cart">
        <view class="header">
          <view class="header-title">
            <view :style="{ 'padding-top': `${paddingTop}px` }">购物车</view>
            <view class="header-address">
              <block v-if="addressList.length > 0">
                <view @click="selectedVisible = true">
                  {{ defaultAddress.city }}{{ defaultAddress.area }}{{ defaultAddress.detail }}
                </view>
                <u-icon size="35rpx" color="#999999" name="arrow-right-double" />
              </block>
              <block v-else>
                <text class="address-toast" @click="goAddress">请添加收货地址！</text>
              </block>
            </view>
          </view>
          <view class="header-total">
            <view><text v-if="cartList.length > 0">共{{ cartList.length }}件商品</text></view>
            <view @click="onManageCart" :class="!isManageStatus ? 'delete' : ''">{{ manageTitel }}</view>
          </view>
        </view>
        <view class="section">
          <view class="section-goods">
            <block v-for="(item, index) in cartList" :key="index">
              <view class="goods-item-info" @click="goGoodsDetail(item)">
                <view class="check-wrap" @click.stop="onSelectGoods(item)">
                  <u-icon size="40rpx" :color="item.isSelected ? !isManageStatus ? '#EA5F5F' : '#32B499' : '#BBBBBB'"
                    :name="item.isSelected ? '/static/icon/checkAct.png' : '/static/icon/check.png'" class="check" />
                </view>
                <view class="imgs">
                  <image :src="item.thumbnail" mode="" />
                </view>
                <view class="goods-item-info_content">
                  <view class="goods-item-info__title">{{ item.name }}</view>
                  <view class="goods-item-info__tags">
                    <view class="goods-item-info__tag"> {{ item.specsName }} </view>
                  </view>
                  <view class="goods-item-info__down">
                    <view>￥<text>{{ item.memberPrice }}</text></view>
                    <view class="algorithm">
                      <view @click.stop="changeNum(item, 'minus')">
                        <u-icon name="minus" size="30rpx" color="#999" />
                      </view>
                      <view> {{ item.number }} </view>
                      <view @click.stop="changeNum(item, 'plus')">
                        <u-icon name="plus" size="30rpx" color="#32B499" />
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </block>
          </view>
        </view>
      </view>
      <!-- 商品小计以及结算按钮 -->
      <view class="cart-settlement">
        <view class="check-all" @click="onSelectAll">
          <u-icon size="40rpx" :color="isCheckAll ? !isManageStatus ? '#EA5F5F' : '#32B499' : '#BBBBBB'"
            :name="isCheckAll ? '/static/icon/checkAct.png' : '/static/icon/check.png'" class="check" />
          <text>全选</text>
        </view>
        <view class="cart-bar__total" v-if="isManageStatus">
          <text class="cart-bar__total--bold text-padding-right">总计</text>
          <!-- totalSum -->
          <view class="sum-prcie">￥<text>{{ totalAmount }}</text></view>
          <text class="cart-bar__total--normal">（不含运费）</text>
        </view>
        <view v-if="isManageStatus" @click="handleToSettle('购物车')" class="account-btn">
          去结算
        </view>
        <view v-else class="account-btn delete-btn" @click="handleDelete">
          删除
        </view>
      </view>
    </block>
    <!-- 购物车空态 -->
    <cart-empty v-else @handleClick="$goPath(2, '/pages/premiumBag/home/index')" />

    <u-popup :show="selectedVisible" @close="selectedVisible = false">
      <view class="popup_selected_product">
        <view class="popup_title">收货地址</view>
        <view class="popup_operate">
          <view @click="$goPath(2, '/pages/premiumBag/mine/addAddress')">新增</view>
          <view @click="$goPath(2, '/pages/premiumBag/mine/address')">管理</view>
        </view>
        <view class="popup-address_list">
          <block v-for="(item, index) in addressList" :key="index">
            <view class="address-list-item" @click="onSelectAddress(item)">
              <view>
                <image v-if="item.isDefault == 1" src="/static/icon/addressDefault.png"
                  mode="aspectFit|aspectFill|widthFix" lazy-load="true" />
                <view v-else class="address-list-item_left">{{ item.isDefaultName }}</view>
                <view class="address-list-item_center">
                  <view>
                    <text class="name">{{ item.name }}</text>
                    <text>{{ item.phone }}</text>
                    <view v-if="item.isDefault == 1" class="default-text">默认</view>
                  </view>
                  <view>{{ item.province }}{{ item.city }}{{ item.area }}{{ item.detail }}</view>
                </view>
              </view>
              <view>
                <u-icon size="40rpx" :color="item.isSelected ? '#32B499' : '#BBBBBB'"
                  :name="item.isSelected ? '/static/icon/checkAct.png' : '/static/icon/check.png'" class="check" />
              </view>
            </view>
          </block>
        </view>
      </view>
    </u-popup>
    <u-modal :show="showWarnConfirm" title="是否删除？" showCancelButton @confirm="confirmDialog"
      @cancel="showWarnConfirm = false"></u-modal>
    <tabbar :currentTab='1' :type="1" />

  </view>
</template>
<script>
import cartEmpty from '@/components/cartEmpty/index';
import { getUserInfo } from '@/common/auth';

export default {
  components: {
    cartEmpty
  },
  data() {
    return {
      userId: getUserInfo().ypdUser?.userId,
      defaultAddress: {},
      cartList: [],
      checkedList: [],
      deleteList: [],
      addressList: [],
      isNotEmpty: false,
      paddingTop: 0,
      isCheckAll: false,
      isManageStatus: true,
      showDelete: false,
      manageTitel: '管理',
      showWarnConfirm: false,
      selectedVisible: false,
      totalSum: 0,
      totalAmount: 0,
    }
  },
  onLoad() { },
  // 调用自定义tabbar的init函数，使页面与tabbar激活状态保持一致
  onShow() {
    let app = uni.getSystemInfoSync()
    this.paddingTop = app.statusBarHeight
    this.checkedList = []
    this.isCheckAll = false
    this.totalAmount = 0
    if (!this.userId) return this.$toast('您还未登录,请先去登录!')
    this.getMyCarList();
    this.getAddressList();
  },
  methods: {
		goAddress(){
			this.$goPath(2,'/pages/premiumBag/mine/address')
		},
    async getAddressList() {
      const { userId } = this;
      let result = await this.$request.miniMyAddress({ userId })
      const { data } = result;
      if (data.length > 0) {
        let spliceArr = [];
        data.forEach((item, index) => {
          item.isSelected = false;
          if (item.isDefault == 0) {
            item.isDefaultName = item.name.slice(0, 1);
          } else {
            spliceArr = data.splice(index, 1);
          }
        });
        if (spliceArr.length > 0) {
          data.unshift(spliceArr[0]);
        }
        data[0].isSelected = true;
        this.addressList = result.data
        this.defaultAddress = result.data[0]
        uni.setStorageSync('cartAddress', result.data[0]);
      } else {
        this.addressList = []
        this.defaultAddress = []
        uni.setStorageSync('cartAddress', {});
      }
    },
    async getMyCarList() {
      const { userId, cartList } = this;
      const result = await this.$request.miniMyCar({ userId })
      let list = result.data
      if (list.length > 0) {
        let sumPrice = 0;
        if (cartList.length == 0) {
          list.map(item => {
            item.isSelected = false;
            sumPrice += Number(item.memberPrice) * Number(item.number);
          });
        } else {
          list.map((item, index) => {
            item.isSelected = false;
            item.isSelected = cartList[index].isSelected;
            sumPrice += Number(item.memberPrice) * Number(item.number);
          });
        }
        setTimeout(() => { this.onCountSum() }, 100);
        this.cartList = list
        this.isNotEmpty = true

      } else {
        this.isNotEmpty = false
      }
    },
    //选择收货地址
    onSelectAddress(detail) {
      const { addressList } = this;
      let addressDetail = {};
      addressList.map(item => {
        if (item.id == detail.id) {
          item.isSelected = true;
          addressDetail = detail;
          uni.setStorageSync('cartAddress', detail);
        } else {
          item.isSelected = false;
        }
      });
      this.addressList = addressList
      this.selectedVisible = false
      this.defaultAddress = addressDetail
    },
    //选择单个或多个商品
    onSelectGoods(goods) {
      const { cartList, deleteList, isManageStatus, checkedList } = this;
      let isCheckAllStatus = true;
      let newArr = [];
      let newDetaleArr = [];
      cartList.map((item, index) => {
        if (item.id == goods.id) {
          item.isSelected = !item.isSelected;
        }
        //是否全选
        if (item.isSelected == true) return;
        isCheckAllStatus = false;
      });
      cartList.map((item, index) => {
        //选中删除
        if (!isManageStatus) {
          if (item.isSelected) {
            newDetaleArr.push(item);
          }
        }
        //选择
        if (item.isSelected) {
          newArr.push(item);
        }
      });
      this.cartList = cartList
      this.isCheckAll = isCheckAllStatus
      this.checkedList = newArr
      this.deleteList = newDetaleArr
      this.onCountSum();
    },
    onCountSum() {
      let list = this.cartList;
      let sumPrice = 0;
      list.forEach(item => {
        if (item.isSelected) {
          sumPrice += Number(item.memberPrice) * Number(item.number);
        }
      });
      this.totalAmount = sumPrice.toFixed(2)
    },
    onManageCart() {
      const { isManageStatus, cartList } = this;
      cartList.map(item => {
        item.isSelected = false;
      })
      this.isManageStatus = !this.isManageStatus
      this.manageTitel = isManageStatus ? '退出管理' : '管理',
        this.cartList = cartList
      this.isCheckAll = false
      this.checkedList = []
      this.deleteList = []
    },
    changeNum(item, type) {
      const { userId } = this;
      let num = item.number;
      if (type == 'minus') {
        if (num > 1) {
          num--;
        }
      } else {
        num++
      }
      const param = {
        carId: item.id,
        number: num,
        productSpecsId: item.productSpecsId,
        productUpId: item.productUpId,
        userId
      };
      this.$request.miniUpdateShoppingCar(param).then(res => {
        if (res.msg == '成功') {
          this.getMyCarList();
        }
      });
    },
    //删除
    handleDelete() {
      const { deleteList } = this;
      console.log(deleteList)
      if (deleteList.length == 0) {
        this.$toast('请选择需要删除的商品');
        return;
      }
      this.showWarnConfirm = true
    },
    confirmDialog() {
      const { deleteList, userId } = this;
      deleteList.map(item => {
        const param = {
          carId: item.id,
          number: item.number,
          productSpecsId: item.productSpecsId,
          productUpId: item.productUpId,
          userId
        };
        this.$request.miniDeleteShoppingCar(param).then(res => {
          if (res.msg == '成功') {
            this.$toast('删除成功');
            this.showWarnConfirm = false
            this.getMyCarList();
          }
        });
      });
    },
    onSelectAll() {
      const { isCheckAll, cartList, checkedList } = this;
      let newDeteteArr = [];
      cartList.map(item => {
        if (!isCheckAll) {
          item.isSelected = true;
          newDeteteArr.push(item);
        } else {
          item.isSelected = false;
          newDeteteArr = [];
        }
      });
      this.cartList = cartList
      this.deleteList = newDeteteArr
      this.checkedList = newDeteteArr
      this.isCheckAll = !isCheckAll
      this.onCountSum()
    },
    handleToSettle(message) {
      const { checkedList, totalAmount } = this;
      if (checkedList.length == 0) {
        this.$toast('请选择商品');
      } else {
        checkedList.map(item => {
          item.id = item.productUpId
        });
        let str = encodeURIComponent(JSON.stringify(checkedList));
        this.cartList = []
        this.$goPath(2, `/pages/premiumBag/goods/confirmOrder?message=${message}&checkedList=${str}&totalAmount=${totalAmount}`)
      }
    },
    //跳转商品详情
    goGoodsDetail(item) {
      const { isManageStatus } = this;
      if (isManageStatus) {
        this.$goPath(2, `/pages/premiumBag/goods/goodsDetail?productId=${item.productUpId}`)
      }
    },


  },
}
</script>
<style scoped>
.container-cart {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding-bottom: calc(180rpx + env(safe-area-inset-bottom));
}

.header {
  background-color: #fff;
  font-size: 28rpx;
  padding: 0 24rpx 24rpx;
}

.header-title {
  color: #666;
}

.header-title>view:first-child {
  font-size: 40rpx;
  font-weight: bold;
  color: #333333;
}

.header-title .header-address {
  display: flex;
  align-items: center;
}

.header-title .header-address .address-toast {
  font-weight: bold;
  color: #333333;
  font-size: 28rpx;
  font-family: 'PingFang SC-Bold';
}


.header-total {
  display: flex;
  justify-content: space-between;
  margin-top: 24rpx;
  color: #333;
}

.section {
  flex: 1;
  padding: 24rpx;
  box-sizing: border-box;
  overflow: scroll;
}

.section::-webkit-scrollbar {
  width: 0;
}

.section-goods {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  padding: 24rpx;
  position: relative;
}

.goods-item-info {
  height: 200rpx;
  display: flex;
  background-color: #fff;
  align-items: center;
  margin-bottom: 24rpx;
}

.goods-item-info:last-child {
  margin: 0;
}

.goods-item-info .check-wrap {
  margin-right: 12rpx;
}

.goods-item-info .check-wrap .unCheck-icon {
  box-sizing: border-box;
  width: 36rpx;
  height: 36rpx;
  border-radius: 20rpx;
  background: #f5f5f5;
  border: 2rpx solid #bbbbbb;
}

.goods-item-info .imgs {
  width: 200rpx;
  height: 200rpx;
  margin-right: 20rpx;
}

.goods-item-info .imgs image {
  width: 100%;
  height: 100%;
  display: block;
  border-radius: 8rpx;
}

.goods-item-info_content {
  flex: 1;
  height: 100%;
  display: flex;
  background: #fff;
  /* border-radius: 0 0 16rpx 16rpx; */
  flex-direction: column;
  justify-content: space-between;
}

.goods-item-info__title {
  flex-shrink: 0;
  display: -webkit-box;
  font-size: 28rpx;
  color: #333;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  word-break: break-word;
  height: 72rpx;
  line-height: 36rpx;
}

.goods-item-info__tags {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.goods-item-info__tag {
  width: 60rpx;
  color: #FF6F40;
  background: transparent;
  font-size: 20rpx;
  font-family: PingFang SC-Regular, PingFang SC;
  border: 1rpx solid #FF6F40;
  padding: 0 8rpx;
  border-radius: 4rpx;
  line-height: 30rpx;
  margin: 0 8rpx 8rpx 0;
  display: block;
  overflow: hidden;
  white-space: nowrap;
  word-break: keep-all;
  text-overflow: ellipsis;
  text-align: center;
}

.goods-item-info {
  display: flex;
  justify-content: space-between;
  color: #EA5F5F;
  font-size: 28rpx;
}

.goods-item-info text {
  font-size: 40rpx;
}

.goods-item-info .goods-item-info_icon {
  color: #999999;
}

.goods-item-info__down {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  color: #EA5F5F;
  font-size: 28rpx;
}

.goods-item-info__down>view:last-child {
  display: flex;
  align-items: center;
}

.goods-item-info__down text {
  font-size: 40rpx;
}

.goods-item-info__down .goods-item-info__down_icon {
  color: #999999;
}

.algorithm {
  width: 190rpx;
  height: 50rpx;
  border-radius: 8rpx 8rpx 8rpx 8rpx;
  border: 1rpx solid #999999;
  margin-left: 24rpx;
  display: flex;
  color: #333333;
}

.algorithm>view {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.algorithm>view:first-child,
.algorithm>view:last-child {
  width: 50rpx;
}

.algorithm>view:nth-child(2) {
  flex: 1;
  border-left: 1rpx solid #999999;
  border-right: 1rpx solid #999999;
}

.cart-settlement {
  width: 100%;
  position: fixed;
  bottom: calc(100rpx + env(safe-area-inset-bottom));
  display: flex;
  justify-content: space-between;
  padding: 24rpx;
  background-color: #fff;
}

.check-all {
  display: flex;
  align-items: center;
}

.check-all>text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333333;
}

.cart-bar__total {
  flex: 1;
  margin-left: 24rpx;
  display: flex;
  align-items: center;
}

.cart-bar__total .cart-bar__total--bold {
  font-size: 28rpx;
  line-height: 40rpx;
  color: #333;
  font-weight: bold;
}

.cart-bar__total .cart-bar__total--normal {
  font-size: 24rpx;
  line-height: 32rpx;
  color: #999;
}

.cart-bar__total .sum-prcie {
  color: #fa4126;
  font-weight: bold;
}

.cart-bar__total .sum-prcie text {
  font-size: 40rpx;
}

.account-btn {
  width: 192rpx;
  height: 80rpx;
  border-radius: 10rpx;
  background-color: #32B499;
  font-size: 28rpx;
  font-weight: bold;
  line-height: 80rpx;
  color: #ffffff;
  text-align: center;
}

.t-dialog__body {
  color: #333 !important;
}

.t-button--text {
  color: #333 !important;
}

.t-button--text.t-button--primary {
  color: #32B499 !important;
}

.popup_selected_product {
  width: 100vw;
  min-height: 600rpx;
  height: 800rpx;
  background: #fff;
  border-radius: 32rpx 32rpx 0 0;
  padding: 0 24rpx;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

.popup_title {
  line-height: 92rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  text-align: center;
  border-bottom: 2rpx solid rgba(241, 241, 241, 0.8);
}

.popup_operate {
  width: 100%;
  display: flex;
  flex-direction: row-reverse;
}

.popup_operate>view {
  padding: 24rpx 0;
  margin-left: 48rpx;
}

.popup-address_list {
  flex: 1;
  overflow: scroll;
}

.popup-address_list::-webkit-scrollbar {
  width: 0;
}

.address-list-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 28rpx;
  font-size: 24rpx;
  color: #666666;
}

.address-list-item:last-child {
  margin-bottom: 0;
}

.address-list-item>view {
  display: flex;
  align-items: center;
}

.address-list-item>view>image {
  width: 60rpx;
  height: 60rpx;
  display: block;
}

.address-list-item .address-list-item_left {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50% 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  color: #FFFFFF;
  background-color: #32B499;
}

.address-list-item_center {
  flex: 1;
  margin-left: 15rpx;
  margin-right: 24rpx;
}

.address-list-item_center>view {
  display: flex;
}

.address-list-item_center>view .name {
  font-size: 28rpx;
  font-family: PingFang SC-Bold, PingFang SC;
  font-weight: bold;
  color: #333333;
  line-height: 33rpx;
  display: block;
  margin-right: 5rpx;
}

.address-list-item_center>view .default-text {
  width: 56rpx;
  border-radius: 4rpx 4rpx 4rpx 4rpx;
  border: 1rpx solid #32B499;
  text-align: center;
  font-size: 20rpx;
  font-family: PingFang SC-Medium, PingFang SC;
  color: #32B499;
  margin-left: 16rpx;
}

.delete {
  color: #EA5F5F;
}

.no-address {
  width: 750rpx;
  padding-top: 30vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  color: #999999;
  font-size: 24rpx;
}

.no-address__icon {
  width: 224rpx;
  height: 224rpx;
}

.no-address__text {
  font-size: 28rpx;
  line-height: 40rpx;
  color: #999999;
  margin-top: 24rpx;
}
</style>